#include <tsin/library/BulletPlainDresser.hpp>

#include <tsin/library/BuiltinImages.hpp>

#include <tsin/runtime/GameRuntime.hpp>
#include <tsin/runtime/BulletRuntime.hpp>
#include <tsin/display/Display.hpp>
#include <tsin/display/Image.hpp>
#include <tsin/display/DecoratedImage.hpp>
#include <tsin/util/Resolution.hpp>
#include <tsin/util/Logger.hpp>
#include <tsin/config/Config.hpp>

#include <cstring>

using namespace tsin;

BulletPlainDresser::BulletPlainDresser()
        : image(0)
{
}

BulletPlainDresser::~BulletPlainDresser()
{
        if (image)
                image->unref();
}

void BulletPlainDresser::init(ImageSeriesId series, BulletShape shape, BulletColor color,
                              BlendStyle blendStyle)
{
        ImageInfo info;

        this->series = series;
        this->shape = shape;
        this->color = color;
        this->blendStyle = blendStyle;

        BuiltinImages::inquiry(series, shape, color, info);
        res = currentGame->config.resolution;
        if (image)
                image->unref();
        image = currentGame->display.openImage(info.path, res);
}

void BulletPlainDresser::reinit()
{
        ImageSeriesId arg1 = static_cast<ImageSeriesId>(arguments[0]->getInt());
        BulletShape   arg2 = static_cast<BulletShape>(arguments[1]->getInt());
        BulletColor   arg3 = static_cast<BulletColor>(arguments[2]->getInt());
        BlendStyle    arg4 = static_cast<BlendStyle>(arguments[3]->getInt());

        switch(nrArguments) {
        case 3:
                if (strcmp(desp, "EEE") == 0)
                        init(arg1, arg2, arg3);
                break;
        case 4:
                if (strcmp(desp, "EEEE") == 0)
                        init(arg1, arg2, arg3, arg4);
                break;
        }
}

void BulletPlainDresser::reset()
{
}

void BulletPlainDresser::dress(BulletRuntime *bullet)
{
        ImageInfo info;
        BuiltinImages::inquiry(series, shape, color, info);

        bullet->image = new DecoratedImage(*image);
        bullet->w = Resolution::pixel2rangeX(res, info.w);
        bullet->h = Resolution::pixel2rangeY(res, info.h);
        bullet->image->init(&info);
        bullet->image->setBlendStyle(blendStyle);

        bullet->series = series;
        bullet->shape = shape;
        bullet->color = color;

        bullet->stage = BULLET_STAGE_LIVE;
}

extern "C" LIBRARY_DLLEXPORT DynamicObject *bindPlainDresser()
{
        return new BulletPlainDresser;
}
